<?php
/*
 * @Date: 2021-01-30 20:23:04
 * @名称: 漫画管理删除用户 也包括自己退出漫画
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑: 初雪桜
 * @LastEditTime: 2021-03-01 20:16:48
 * @FilePath: /Site/app/useradmin/controller/Comics/User/UserDeleteUser.php
 */

namespace app\useradmin\controller\Comics\User;

use app\BaseController;
use app\useradmin\controller\DataBaseController\AuthorAndChineseTeam;
use app\useradmin\controller\DataBaseController\LogController;
use think\facade\Db;

class UserDeleteUser extends BaseController
{
    /**
     * @方法名: 删除用户 / 协作者删除用户
     * @作者: 初雪桜
     * @信息: 作者直接删除 协作者删除需要作者审核
     * @param Json $user_info
     * @param Json $postData
     * @return Json
     */
    public function deleteUser($user_info, $postData)
    {

        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $author_and_chinese_team = Db::table("author_and_chinese_team")
                ->where([
                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                    "state" => 0,
                ])
                ->field([
                    '_id',
                    'author_or_chinese_team',
                ])
                ->find();

            if (!$author_and_chinese_team && $author_and_chinese_team['author_or_chinese_team'] !=  $postData['initListType']) { //判断有没有查询到用户 并且 用户状态和传入的不一致
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-10000")->getContent(), true);
            }
            $MyRights = Db::table("author_and_chinese_team")
                ->where([
                    "user_id" => $user_info['_id'],
                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                    "state" => 0,
                ])
                ->field([
                    '_id',
                    'author_or_chinese_team',
                ])
                ->find();
            switch ($MyRights["author_or_chinese_team"]) {
                case '0': //我是创作者
                    $authorCount = Db::table("author_and_chinese_team")
                        ->where([
                            "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                            "state" => 0,
                            "author_or_chinese_team" => 0,
                        ])
                        ->field([
                            '_id',
                        ])
                        ->select();
                    if (count($authorCount) > 1) { //判断一下作者总数除了我之外是不是还有作者
                        if (
                            $user_info["_id"] ==
                            $postData['jsonDecodeinitListUserInfo']['user_id']
                        ) { //判断是不是删除自己
                            $msg =  "创作者  " . $user_info["_id"] . " 删除了自己 " . $postData["jsonDecodeUserInfo"]["user_id"];;
                            $exp_state = 7;
                        } else { //不是删除我自己
                            $msg =  "创作者  " . $user_info["_id"] . " 删除了 " . $postData["jsonDecodeUserInfo"]["user_id"];;
                            $exp_state = 2;
                        }
                        $LogController = new LogController($this->app);
                        $LogController->insert_AACT_log(
                            $postData['jsonDecodeUserInfo']['book_id'],
                            $postData['jsonDecodeUserInfo']['user_id'],
                            $postData['jsonDecodeinitListUserInfo']['user_id'], //新用户id 继承时候会用到
                            $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_id一致
                            $msg,
                            1,
                            $user_info["_id"],
                            [
                                "implement_user_id" =>  $user_info['_id'],
                                "implement_time" => date("Y-m-d H:i:s"),
                            ]
                        );
                        Db::table('author_and_chinese_team')
                            ->where([
                                "_id" => $author_and_chinese_team['_id'],
                                "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                "state" => 0,
                            ])
                            ->update([
                                "state" => 1,
                                "is_deleted" => 1,
                                "exp_state" => $exp_state,
                            ]);
                    } else { //如果就我一个作者
                        if (
                            $user_info["_id"] ==
                            $postData['jsonDecodeinitListUserInfo']['user_id']
                        ) { //判断是不是删除自己
                            return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-10001")->getContent(), true);
                        } else { //不是删除我自己
                            $msg =  "创作者  " . $user_info["_id"] . " 删除了 " . $postData["jsonDecodeUserInfo"]["user_id"];;
                            $exp_state = 2;
                            $LogController = new LogController($this->app);
                            $LogController->insert_AACT_log(
                                $postData['jsonDecodeUserInfo']['book_id'],
                                $postData['jsonDecodeUserInfo']['user_id'],
                                $postData['jsonDecodeinitListUserInfo']['user_id'], //新用户id 继承时候会用到
                                $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_id一致
                                $msg,
                                1,
                                $user_info["_id"],
                                [
                                    "implement_user_id" =>  $user_info['_id'],
                                    "implement_time" => date("Y-m-d H:i:s"),
                                ]
                            );
                            Db::table('author_and_chinese_team')
                                ->where([
                                    "_id" => $author_and_chinese_team['_id'],
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "state" => 0,
                                ])
                                ->update([
                                    "state" => 1,
                                    "is_deleted" => 1,
                                    "exp_state" => $exp_state,
                                ]);
                        }
                    }

                    break;

                case '1': //我是协作者
                    try {
                        if (
                            $user_info["_id"] ==
                            $postData['jsonDecodeinitListUserInfo']['user_id']
                        ) { //判断是不是删除自己
                            $LogController = new LogController($this->app);
                            $LogController->insert_AACT_log(
                                $postData['jsonDecodeUserInfo']['book_id'],
                                $postData['jsonDecodeUserInfo']['user_id'],
                                $postData['jsonDecodeUserInfo']['user_id'], //新用户id 继承时候会用到
                                $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_id一致
                                "用户  " . $user_info["_id"] . " 以退出", //信息
                                1,
                                $user_info["_id"],
                                [
                                    "implement_user_id" =>  $user_info['_id'],
                                    "implement_time" => date("Y-m-d H:i:s"),
                                ]
                            );
                            Db::table('author_and_chinese_team')
                                ->where([
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "state" => 0,
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_id一致
                                ])
                                ->update([
                                    "edit_delete_user" => 0,
                                    "edit_inherit_users" => 0,
                                    "edit_edit_user" => 0,
                                    "state" => 1,
                                    "exp_state" => 7,
                                    "is_deleted" => 1,
                                ]);
                        } else { //不是删除我自己
                            $LogController = new LogController($this->app);
                            $LogController->insert_AACT_log(
                                $postData['jsonDecodeUserInfo']['book_id'],
                                $postData['jsonDecodeUserInfo']['user_id'],
                                $postData['jsonDecodeUserInfo']['user_id'], //新用户id 继承时候会用到
                                $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_id一致
                                "用户  " . $user_info["_id"] . " 申请删除删除 " . $postData["jsonDecodeUserInfo"]["user_id"], //信息
                                0,
                                $user_info["_id"],

                            );
                            Db::table('author_and_chinese_team')
                                ->where([
                                    "user_id" => $postData['jsonDecodeUserInfo']['user_id'],
                                    "book_id" => $postData['jsonDecodeUserInfo']['book_id'],
                                    "state" => 0,
                                    "_id" => $author_and_chinese_team['_id'], //操作的 author_and_chinese_team 表中的_id一致
                                ])
                                ->update([
                                    "edit_delete_user" => 0,
                                    "edit_inherit_users" => 0,
                                    "edit_edit_user" => 0,
                                    "exp_state" => 10,
                                ]);
                        }
                    } catch (\Throwable $th) {
                        return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-undefined")->getContent(), true);
                    }
                    break;

                default:
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-Delete-undefined")->getContent(), true);
                    break;
            }
        } else {
            return $postData;
        }
    }
    /**
     * @方法名: 拒绝删除用户
     * @作者: 初雪桜
     * @信息: 协作者申请删除用户 拒绝删除
     * @param Json $user_info
     * @param Json $postData
     * @return Json
     */
    public function RefuseToDeleteUser($user_info, $postData)
    {
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $meIsAuthor = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return errorJsonReturn('User permission error', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
            $delete_user_info = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                    "state" => 0,
                    "exp_state" => 10,
                ])
                ->field(["_id"])
                ->find();
            if ($delete_user_info) { //判断被删除的人员是否还在表中
                try {
                    $deleteState = Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "state" => 0,
                            "exp_state" => 10,
                        ])
                        ->update([
                            "edit_delete_user" => 1,
                            "edit_inherit_users" => 1,
                            "edit_edit_user" => 1,
                            "exp_state" => null,
                        ]);
                    if ($deleteState) {
                        $LogController = new LogController($this->app);
                        $LogController->update_aact_log(
                            $postData['bookId'],
                            $delete_user_info["_id"],
                            2,
                            $user_info["_id"],
                        );
                        return successJsonReturn();
                    } else {
                        return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                    }
                } catch (\Throwable $th) {
                    //throw $th;
                }
            } else {
                return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
        } else {
            return $postData;
        }
    }
    /**
     * @方法名: 同意删除用户
     * @作者: 初雪桜
     * @信息: 协作者申请删除用户 允许删除
     * @param Json $user_info
     * @param Json $postData
     * @return Json
     */
    public function AgreeToDeleteUser($user_info, $postData)
    {
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $meIsAuthor = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return errorJsonReturn('User permission error', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
            $delete_user_info = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                    "state" => 0,
                    "exp_state" => 10,
                ])
                ->field(["_id"])
                ->find();
            if ($delete_user_info) { //判断被删除的人员是否还在表中
                try {
                    $deleteState = Db::table('author_and_chinese_team')
                        ->where([
                            "book_id" => $postData['bookId'],
                            "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                            "state" => 0,
                            "exp_state" => 10,
                        ])
                        ->update([
                            "state" => 1,
                            "exp_state" => 2,
                            "is_deleted" => 1,
                        ]);
                    if ($deleteState) {
                        $LogController = new LogController($this->app);
                        $LogController->update_aact_log(
                            $postData['bookId'],
                            $delete_user_info["_id"],
                            1,
                            $user_info["_id"],
                        );
                        return successJsonReturn();
                    } else {
                        return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
                    }
                } catch (\Throwable $th) {
                    //throw $th;
                }
            } else {
                return errorJsonReturn('No such user', '请刷新网页再试' . __LINE__); //!当用户已处于其他状态时候 
            }
        } else {
            return $postData;
        }
    }
    public function RecoveryUser($user_info, $postData)
    {
        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            $meIsAuthor = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $user_info["_id"],
                    "author_or_chinese_team" => 0,
                    "state" => 0,
                ])
                ->count();
            if (!$meIsAuthor) { //如果登录的用户是管理员的在执行
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-RecoveryUser-10000")->getContent(), true);
            }
            $recoveryUser_user_info = Db::table('author_and_chinese_team')
                ->where([
                    "book_id" => $postData['bookId'],
                    "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                    "state" => 1,
                    "exp_state" => 2,
                ])
                ->field(["_id"])
                ->find();
            if (!$recoveryUser_user_info) { //判断被删除的人员是否还在表中
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-RecoveryUser-10001")->getContent(), true);
            }
            try {
                $recoveryUserState = Db::table('author_and_chinese_team')
                    ->where([
                        "book_id" => $postData['bookId'],
                        "user_id" => $postData['jsonDecodeinitListUserInfo']["user_id"],
                        "state" => 1,
                        "exp_state" => 2,
                    ])
                    ->update([
                        "state" => 0,
                        "exp_state" => null,
                        "is_deleted" => 0,
                    ]);
                if ($recoveryUserState) {
                    $LogController = new LogController($this->app);
                    $LogController->insert_AACT_log(
                        $postData['bookId'],
                        $postData['jsonDecodeinitListUserInfo']["user_id"],
                        $postData['jsonDecodeinitListUserInfo']["user_id"], //新用户id 继承时候会用到
                        $recoveryUser_user_info['_id'], //!操作的表的id
                        "创作者 " . $user_info['_id'] . " 恢复了用户" . $postData['jsonDecodeinitListUserInfo']["user_id"], //!操作说明
                        1,
                        $user_info["_id"],
                        [
                            "implement_user_id" =>  $user_info['_id'],
                            "implement_time" => date("Y-m-d H:i:s"),
                        ]
                    );

                    return successJsonReturn();
                } else {
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-RecoveryUser-10001")->getContent(), true);
                }
            } catch (\Throwable $th) {
                //throw $th;
            }
        } else {
            return $postData;
        }
    }
    /**
     * @方法名: 删除状态异常的用户
     * @作者: 初雪桜
     * @信息: 作者直接删除 协作者删除需要作者审核
     * @param Json $user_info
     * @param Json $postData
     * @return Json
     */
    public function DeleteStatusExceptionUser($user_info, $postData)
    {

        if ($postData['code'] == 200) {
            $postData = $postData['data'];
            //@b 查询用户权限
            $AuthorAndChineseTeam = new AuthorAndChineseTeam($this->app);
            $MyRights =  $AuthorAndChineseTeam->Select(
                $user_info['_id'],
                $postData['jsonDecodeUserInfo']['book_id'],
                ['author_or_chinese_team', "_id", "edit_delete_user", "state"]
                //@i 查询权限 1。作者还是协作者 2.id 3。删除用户权限 4.用户状态
            ); //查询用户权限
            if ($MyRights["code"] == 200) {
                $MyRights = $MyRights["data"];
            } else {
                return $MyRights;
            }

            switch ($MyRights["state"]) { //判断用户状态 状态 0正常 1已停用 2已删除
                case '0':
                    # 用户正常
                    break;
                case '1':
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10000")->getContent(), true);
                    break;
                case '2':
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10001")->getContent(), true);
                    break;
                default:
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10001")->getContent(), true);
                    break;
            }

            if ($MyRights["edit_delete_user"] != 1) { //判断用户是否有删除权限
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10005")->getContent(), true);
            }

            switch ($MyRights["author_or_chinese_team"]) { //判断用户是否是作者
                case '0': //@i 是作者

                    break;
                case '1': //@i 是协作者
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10002")->getContent(), true);
                    break;
                default:
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-undefined")->getContent(), true);
                    break;
            }
            $AuthorAndChineseTeam = new AuthorAndChineseTeam($this->app);
            $YouRights =  $AuthorAndChineseTeam->Select( //被操作者用户查询
                $postData['jsonDecodeUserInfo']['user_id'],
                $postData['jsonDecodeUserInfo']['book_id'],
                ['author_or_chinese_team', "_id",  "state", "is_deleted", "user_id"]
                //@i 查询权限 1。作者还是协作者 2.id 3.用户状态 4.是否允许删除自己 5.用户id
            ); //查询用户权限
            if ($YouRights["code"] == 200) {
                $YouRights = $YouRights["data"];
            } else {
                return $YouRights;
            }
            if ($YouRights['is_deleted'] != 1) {
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10003")->getContent(), true); //用户状态 禁止删除
            }
            switch ($YouRights["author_or_chinese_team"]) { //判断用户是否是作者
                case '0': //@i 是作者
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10004")->getContent(), true); //
                    break;
                case '1': //@i 协作者
                    break;
                default:
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-undefined")->getContent(), true);
                    break;
            }

            switch ($YouRights["state"]) { //判断用户状态 状态 0正常 1异常
                case '0':
                    # 用户正常
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10003")->getContent(), true);
                    break;
                case '1':
                    # 用户 异常 
                    break;
                default:
                    return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10001")->getContent(), true);
                    break;
            }


            //@i 此刻已经验证完了我是作者权限无异常
            $AuthorAndChineseTeam = new AuthorAndChineseTeam($this->app);
            $UpdateAuthorAndChineseTeamTable = $AuthorAndChineseTeam->Update(
                $postData['jsonDecodeUserInfo']['user_id'],
                $postData['jsonDecodeUserInfo']['book_id'],
                $YouRights["_id"],
                [
                    "exp_state" => 13,
                    "edit_delete_user" => 0,
                    "edit_inherit_users" => 0,
                    "edit_edit_user" => 0,
                    "edit_add_user" => 0,
                    "edit_sever_comics_info" => 0,
                    "edit_add_project" => 1,
                    "delete_time" => date("Y-m-d H:i:s"),
                    "is_deleted" => 0,
                ]
            );
            if ($UpdateAuthorAndChineseTeamTable['code'] != 200) {
                return json_decode(errorJsonReturn("AuthorAndChineseTeam-DeleteStatusExceptionUser-10006")->getContent(), true);
            } else {
                return json_decode(successJsonReturn()->getContent(), true);
            }
        } else {
            return $postData;
        }
    }
}
